<?php

namespace app\api\controller;

use app\ApiBaseController;
use EasyAdmin\upload\Uploadfile;

class Common extends ApiBaseController
{
    /**
     * 上传图片
     */
    public function upload()
    {
        $data = [
            'file'   =>  $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|图片类型有误'  => "in:{$uploadConfig['upload_allow_type']}",
            'file|图片'                 => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->apiValidate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        if ($upload['save'] == true) {
            return result(0, $upload['msg'], ['id'=>$upload['id'], 'url' => $upload['url']]);
        } else {
            return result(1, $upload['msg']);
        }
    }
}